package com.example.myprojectoffeixue;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.localization.FristActivity;
import com.localization.Gateway;
import com.localization.GlobalValue;
import com.localization.SocketCmdsDistribute;
import com.localization.SocketUdpClient;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
//第一个界面,作用是停止1.5秒，跳转到登录界面，跳转的同时附加动画效果；

public class ShanPingActivity extends Activity {
    public static boolean reconnect;
    //利用handler机制进行跳转界面
    Intent it = null;
    boolean flag2;
    String UserId;
    String SocketToken;
    MyApplication m_app;
    String UserName;
    String PassWord;
    boolean isexit;
    SharedPreferences sp;
    PackageInfo pi;
    public  static boolean flag;
    byte cmd[] = {(byte) 0xfc,0x00,0x0b,0x00,0x01,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff,0x01,(byte)0xff,0x01,(byte)0xf5};
    byte heart[] = {(byte) 0xfc,0x00,0x0b,0x00,0x01,0x00,0x08,(byte)0xb8,0x76,0x0b,0x14,0x01,0x01,0x06,(byte) 0xd5};


    Handler hand = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 20) {
                startActivity(it);
                overridePendingTransition(R.anim.in, R.anim.out);
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_shan_ping);
        flag=true;//开线程连接；
        flag2=true;//判断条件线程
        checkNetworkState(getBaseContext());
        init();
    }
    private void init() {
        reconnect=false;//不连接;
        sp = getSharedPreferences("first", MODE_PRIVATE);
        MyApplication.localflag=false;
        m_app = (MyApplication) getApplication();
        GlobalValue.tcpclient=null;
        String Devicelist=sp.getString("deviceList",null);
        if(Devicelist!=null){
            m_app.m_gateway = (ArrayList<GateWay>) JSON.parseArray(Devicelist, GateWay.class);
            SocketCmdsDistribute.m_gateway = m_app.m_gateway;
        }
        UserName = sp.getString("username", null);
        PassWord = sp.getString("password", null);
        isexit = sp.getBoolean("isexit", false);
        m_app.username=UserName;
        m_app.authToken = sp.getString("authToken", null);
        m_app.userId = sp.getString("UserId", null);
        m_app.authId=sp.getString("authId",null);
        update();
    }

    private void GetDeviceList() {
        if (m_app.userId != null) {
            GateWay Gw = new GateWay();
            Gw.userId = m_app.userId;
            Gw.status = 1;
            String j = JSON.toJSONString(Gw);
            j = AESUtil.encrypt(j);
            HttpUtils httpUtils = new HttpUtils();
            RequestParams params = new RequestParams();
            params.setHeader("Content-Type", "application/json");
            try {
                params.setBodyEntity(new StringEntity(j, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/device/getDeviceList", params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            HttpConnection.toastLog("网络异常", ShanPingActivity.this);
                            Log.d("exception",arg0.toString()+"--"+arg1);
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            if (arg0.result != null && !("".equals(arg0.result))) {
                                arg0.result = AESUtil.decrypt(arg0.result);
                                Log.d("result",arg0.result);
                                JSONObject jb = JSONObject.parseObject(arg0.result);
                                String status=jb.getString("status");
                                if("0".equals(status)) {
                                    JSONArray ja = jb.getJSONArray("deviceList");
                                    sp.edit().putString("deviceList",ja.toString()).commit();
                                    m_app.m_gateway = (ArrayList<GateWay>) JSON.parseArray(ja.toString(), GateWay.class);
                                    SocketCmdsDistribute.m_gateway = m_app.m_gateway;
                                 //   if (m_app.m_gateway.size() != 0) {
                                        m_app.username=UserName;
                                        it = new Intent(ShanPingActivity.this, MainActivity.class);
                                        hand.sendEmptyMessage(20);
                                        MyApplication.localflag=false;
                                   // } else {
                                     //   m_app.username=UserName;
                                      //  it = new Intent(ShanPingActivity.this, FristLogin.class);
                                      //  hand.sendEmptyMessage(20);
                                   // }
                                }else{
                                    HttpConnection.toastLog("服务器错误", ShanPingActivity.this);
                                }
                            } else {
                                HttpConnection.toastLog("服务器错误", ShanPingActivity.this);
                            }
                        }

                    });

        }
    }

    public void update() {
        PackageManager pm = getPackageManager();
        try {
            pi = pm.getPackageInfo(getPackageName(), 0);
        } catch (Exception e) {
        }

        int versionCode = pi.versionCode;
        //int versionCode=0;
        String os = "Android";
        Websocketutil ws = new Websocketutil(os, versionCode);
        String j = JSON.toJSONString(ws);
        j = AESUtil.encrypt(j);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(j, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/user/updateApp", params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.d("11111111111111","222222222222222");
                runner2.start();
            }


            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                if (arg0.result != null && !("".equals(arg0.result))) {
                    arg0.result = AESUtil.decrypt(arg0.result);
                    JSONObject j2 = JSONObject.parseObject(arg0.result);
                    String status = j2.getString("status");
                    if ("0".equals(status)) {
                        JSONObject j1 = j2.getJSONObject("latestVersion");
                        if (j1 == null) {
                            if (PassWord != null && !isexit) {
                               GetDeviceList();
                                /*it = new Intent(ShanPingActivity.this, FristActivity.class);
                                hand.sendEmptyMessage(20);*/
                            } else {
                                it = new Intent(ShanPingActivity.this, LoginActivity.class);
                                hand.sendEmptyMessage(20);
                            }
                        } else {
                        it = new Intent(ShanPingActivity.this, LoginActivity.class);
                        hand.sendEmptyMessage(20);
                    }

                }else{
                        it = new Intent(ShanPingActivity.this, LoginActivity.class);
                        hand.sendEmptyMessage(20);
                    }
                }else{
                    it = new Intent(ShanPingActivity.this, LoginActivity.class);
                    hand.sendEmptyMessage(20);
                }
            }
        });
    }

    public  void checkNetworkState(Context context){
        Log.d("内网检测开始","开始");
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
            if(networkInfo!=null){
            //1.判断是否有网络连接
            boolean networkAvailable = networkInfo.isAvailable();
            //2.获取当前网络连接的类型信息
            int networkType = networkInfo.getType();
            if(ConnectivityManager.TYPE_WIFI == networkType){
                runner.start();
            }else if(ConnectivityManager.TYPE_MOBILE == networkType){
                //当前为mobile网络
            }
        }
        }
    }
//udp发送判断内网
    Thread runner=new Thread(){
        @Override
        public void run() {
            Gateway gateway;
            System.out.println("Hello World!");
            gateway = new Gateway();
            m_app.udp = new SocketUdpClient(gateway);
            m_app.udp.connect("", "255.255.255.255", 8200);
            gateway.working();
            GlobalValue.mGateway = gateway;
            while (flag){
                for(int i=0;i<2;i++){
                    if (GlobalValue.tcpclient == null) {
                        Log.d("Udp命令", "UDP发送");
                        if (m_app.udp!=null) {
                            m_app.udp.send(cmd);
                        }
                        try {
                            Thread.currentThread().sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                }}
                flag=false;
                reconnect=false;
            }
            super.run();
        }
    };

//判断跳转条件

    Thread runner2=new Thread(){
        @Override
        public void run() {
            while (flag2){
                try {
                    sleep(1000);
                if(isexit){
                    it = new Intent(ShanPingActivity.this, LoginActivity.class);
                    hand.sendEmptyMessage(20);
                }else {
                    if (GlobalValue.tcpclient == null) {
                        flag = false;
                        if (m_app.udp != null) {
                            m_app.udp.close();
                        }
                        it = new Intent(ShanPingActivity.this, LoginActivity.class);//没有退出、不能连接外网，无udp反馈情况
                        hand.sendEmptyMessage(20);
                    } else {
                        Log.d("判断完成", "完成");
                        it = new Intent(ShanPingActivity.this, MainActivity.class);//没有退出，不能连接外网，有udp反馈情况
                        hand.sendEmptyMessage(20);
                    }
                }
                flag2=false;
                MyApplication.localflag = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            super.run();
        }
    };
}